//
//  DebtDetailTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/7.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import MJRefresh
import DZNEmptyDataSet

class DebtDetailTableViewController: BaseTableViewController {
    
    var page = 1
    
    var dataArray = [DebtDetailModel]()
    
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        
        view.backClosure = { [weak self] in
            self?.userSettleArrears()
        }
        
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "欠款详情"
        self.tableView.rowHeight = 80
        self.setRightBarButton(title: "全部归还", imageName: "", action: #selector(self.rightBarButtonAction), titleColor: "#000000")
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.page = 1
            self?.getUserArrears()
        })
        self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: { [weak self] in
            self?.page = (self?.page)! + 1
            self?.getUserArrears()
        })
        self.tableView.emptyDataSetDelegate = self
        self.tableView.emptyDataSetSource = self
        
        PKhud.show()
        self.getUserArrears()
    }
    
    @objc func rightBarButtonAction(){
        guard self.dataArray.count != 0 else {
            PKhud.showText(text: "您现在没有欠款哦~")
            return
        }
        self.alertView.show(withTitle: "确定要全部归还吗？")
    }
    
    
    func userSettleArrears(){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.userSettleArrears.rawValue, parameters: ["orderId":0]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                PKhud.showText(text: "归还成功~")
                self.getUserArrears()
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }

    
    func getUserArrears(){
        HttpRequest.requestData(.post, URLString: Api.userArrears.rawValue, parameters: ["pageNum":self.page,"pageSize":10]) { (result) in
            PKhud.hiden()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            if result["msg"] as! String == "success"{
                
                if let array = [DebtDetailModel].deserialize(from: result["data"] as? [Any]) as? [DebtDetailModel] {
                    if self.page == 1 {
                        self.dataArray = array
                    }else{
                        self.dataArray = self.dataArray + array
                    }
                    if array.count < 10 {
                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    }
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DebtTableViewCell", for: indexPath) as! DebtTableViewCell
        cell.reload(withModel: self.dataArray[indexPath.row])
        cell.backClosure = { [weak self] in
            self?.getUserArrears()
        }

        return cell
    }
}
extension DebtDetailTableViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let str = "暂无欠款,信用超棒的哦~"
        let attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14),
                                 NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "666666")], range: NSRange.init(location: 0, length: str.count))
        
        return attribute
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage.init(named: "img_Defaultheadimage")
    }
}








